#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Export Item Detabase Toolkit

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_36"
__date__    = "2014/01/05"
__license__ = 'LGPL'

# ------------------------------------------------------------
## Import Section
# ------------------------------------------------------------
# Python
import json
from xml.dom.minidom import getDOMImplementation

# ESiPC

# Mikan
from mikan.idt import AbstractMikanItemDBToolkit
from mikan.core import MIKAN

# ------------------------------------------------------------
## Variable Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Function Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Class Section
# ------------------------------------------------------------
class MIKAN_IDT_EXPORT(MIKAN):
	TYPE_TEXT = "text"
	TYPE_XML = "xml"
	TYPE_CSV = "csv"
	TYPE_JSON = "json"
#	TYPE_RSS = "rss"

class AbstractMikanExportIDT(AbstractMikanItemDBToolkit, MIKAN_IDT_EXPORT):
	def __init__(self, itemdb):
		super(AbstractMikanExportIDT, self).__init__(itemdb)

class MikanExportIDT(AbstractMikanExportIDT):
	def __init__(self, itemdb):
		super(MikanExportIDT, self).__init__(itemdb)

	def _get_attributes(self, form):
		if not form:
			return None

		attributes = []
		for field in form.sorted_fields():
			if not field.ispassword:
				if field.isvisibled:
					attributes.append(field.attribute)
		return attributes

	def _loadeds(self, entities=None, attributes=None, todisplay=True):
		result = {}
		for entity in entities:
			a = attributes
			if not a:
				a = entity.sorted_attributes()
			self._loaded(result, a, todisplay)

	def _loaded(self, result, attributes=None, todisplay=True):
		if todisplay:
			for attribute in attributes:
				if attribute != None:
					if attribute.list != None:
						if attribute.list.isentitylist:
							if result.has_key(attribute):
								attribute.list.FList = result[attribute]
							else:
								attribute.list.build_list(self.itemdb)
								result[attribute] = attribute.list.FList

	def exports(self, atype, entities, form=None, custom=None, columns=True, todisplay=True):
		if not entities:
			return None
		attributes = self._get_attributes(form)
		self._loadeds(entities, attributes, todisplay)

		return self.export_entities(atype, entities, attributes, custom, columns, todisplay)

	def export(self, atype, entity, form=None, custom=None, columns=True, todisplay=True):
		if entity == None:
			return None

		attributes = self._get_attributes(form)
		self._loadeds([entity], attributes, todisplay)

		return self.export_entity(atype, entity, attributes, custom, columns, todisplay)

	def export_entities(self, atype, entities, attributes=None, custom=None, columns=True, todisplay=True):
		a = attributes
		if (not a) and (len(entities) > 0):
			a = entities[0].sorted_attributes()

		if custom:
			return custom(self, entities, a, columns, todisplay)
		if atype == MIKAN_IDT_EXPORT.TYPE_JSON:
			return self.export_json_entities(entities, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_CSV:
			return self.export_csv_entities(entities, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_XML:
			return self.export_xml_entities(entities, a, columns, todisplay)
		return None

	def export_entity(self, atype, entity, attributes=None, custom=None, columns=True, todisplay=True):
		a = attributes
		if not a:
			a = entity.sorted_attributes()

		if custom:
			return custom(self, entity, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_JSON:
			return self.export_json_entity(entity, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_CSV:
			return self.export_csv_entity(entity, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_XML:
			return self.export_xml_entity(entity, a, columns, todisplay)
		elif atype == MIKAN_IDT_EXPORT.TYPE_TEXT:
			return self.export_text_entity(entity, a, columns, todisplay)
		return None

	def export_json_entities(self, entities, attributes, columns, todisplay=True):
		data = {}
		if columns:
			data["colume"] = self.export_json_entity_columns(entities[0], attributes)
		values = {}
		for entity in entities:
			values[entity.getIDValue()] = self.export_json_entity_values(entity, attributes, todisplay)
		data["item"] = values
		return json.dumps(data, indent=2, ensure_ascii=False)

	def export_csv_entities(self, entities, attributes, columns, todisplay=True):
		colums = ""
		if columns:
			colums = self.export_csv_entity_colums(entities[0], attributes)

		values = ""
		for entity in entities:
			values = values + self.export_csv_entity_values(entity, attributes, todisplay)
		return colums + values

	def export_xml_entities(self, entities, attributes, columns, todisplay=True):
		dom = getDOMImplementation()
		xml = dom.createDocument(None, "mikan", None)
		if columns:
			xml = self.export_xml_entity_colums(entities[0], xml, attributes)

		for entity in entities:
			self.export_xml_entity_values(entity, xml, attributes, todisplay)
		return xml

	def export_json_entity_columns(self, entity, attributes):
		columns = {}
		columns["class"] = "class"
		for attribute in attributes:
			columns[attribute.itemname] = attribute.itemcaption

		return columns

	def export_json_entity_values(self, entity, attributes, todisplay=True):
		values = {}
		values["class"] = entity.itemfullclassname

		vs = {}
		for attribute in attributes:
			v = ""
			nvalue = entity[attribute.definename]
			nv = unicode(nvalue)
			if nv == "None":
				nv = ""
			if (attribute.list == None) or (not todisplay):
				v = nv
			else:
				v = attribute.to_display_value(nvalue)
			vs[attribute.definename] = v
		values.update(vs)

		return values

	def export_json_entity(self, entity, attributes, columns, todisplay=True):
		data = {}
		if columns:
			data["colume"] = self.export_json_entity_columns(entity, attributes)
		data["item"] = self.export_json_entity_values(entity, attributes, todisplay)
		return json.dumps(data, indent=2, ensure_ascii=False)

	def export_csv_entity_colums(self, entity, attributes):
		columns = "\"%s\",\"%s\",\"%s\",\"%s\"," % ("class", "id", "name", "caption")
		for attribute in attributes:
			columns = "%s\"%s\"," % (columns, attribute.itemcaption)

		return u"%s\n" % (columns)

	def export_csv_entity_values(self, entity, attributes, todisplay=True):
		values = "\"%s\",\"%s\",\"%s\",\"%s\"," % (entity.itemfullclassname, str(entity.getIDValue()), str(entity.definename), entity.itemcaption)

		for attribute in attributes:
			nvalue = entity[attribute.definename]
			nv = unicode(nvalue)
			if nv == "None":
				nv = ""
			if (attribute.list == None) or (not todisplay):
				v = nv
			else:
				v = attribute.to_display_value(nvalue)

			values = "%s\"%s\"," % (values, v)
		return u"%s\n" % (values)

	def export_csv_entity(self, entity, attributes, columns, todisplay=True):
		values = self.export_csv_entity_values(entity, attributes, todisplay)
		if not columns:
			return values

		c = self.export_csv_entity_colums(entity, attributes)
		return c + values

	def export_xml_entity_colums(self, entity, xml, attributes):
		return xml

	def export_xml_entity_values(self, entity, xml, attributes, todisplay=True):
#		try:
		o = xml.createElement("o")
		xml.documentElement.appendChild(o)
		o.setAttribute("class", entity.itemfullclassname)
		o.setAttribute("id", str(entity.getIDValue()))
		o.setAttribute("name", str(entity.definename))
		o.setAttribute("caption", entity.itemcaption)

		for attribute in attributes:
			a = xml.createElement("attribute")
			o.appendChild(a)
			a.setAttribute("name", attribute.definename)
			a.setAttribute("caption", attribute.itemcaption)

			nvalue = entity[attribute.definename]
			nv = unicode(nvalue)
			if nv == "None":
				nv = ""
			a.setAttribute("value", nv)

			if (attribute.list == None) or (not todisplay):
				a.setAttribute("display", nv)
			else:
				value = unicode(attribute.to_display_value(nvalue))
				a.setAttribute("display", value)

#		except:
#			self.logger.error(traceback.format_exc())
		return xml

	def export_xml_entity(self, entity, attributes, columns, todisplay=True):
		dom = getDOMImplementation()
		xml = dom.createDocument(None, "mikan", None)
		if columns:
			xml = self.export_xml_entity_colums(entity, xml, attributes)

		return self.export_xml_entity_values(entity, xml, attributes)

	def export_text_entity(self, entity, attributes, columns, todisplay=True):
		lines = ""

		for attribute in attributes:
			cap = attribute.itemcaption

			nvalue = entity[attribute.definename]
			nv = unicode(nvalue)
			if nv == "None":
				nv = ""
			if (attribute.list == None) or (not todisplay):
				v = nv
			else:
				v = attribute.to_display_value(nvalue)

			lines = u"%s%s%s\n" % (lines, cap, v)

		return lines

# ------------------------------------------------------------
## Main Section
# ------------------------------------------------------------
if __name__ == '__main__':
	pass

# ------------------------------------------------------------
